package com.rjwh.dingdong.client.activity.image;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.adapter.AlbumPhotoListAdpater;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.localbean.ImageBucket;
import com.rjwh.dingdong.client.bean.localbean.ImageItem;
import com.rjwh.dingdong.client.util.AlbumHelper;
import com.rjwh.dingdong.client.util.ToastUtil;
import com.rjwh.dingdong.client.view.ListImageDirPopupWindow;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 选择相册
 *
 * @author 王博扬
 * @ClassName PhotoListActivity
 * @Description TODO(这里用一句话描述这个类的作用)
 * @date 2015-9-15 下午4:27:46
 * @history 1.YYYY-MM-DD
 * author:
 * description:
 */
public class PhotoListActivity extends BaseActivity {


    @BindView(R.id.community_post_publish_center_tv)
    TextView communityPostPublishCenterTv;
    @BindView(R.id.community_post_publish_center_ll)
    LinearLayout communityPostPublishCenterLl;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.album_bucket_photo_list_gv)
    GridView photoGv;
    @BindView(R.id.id_choose_dir)
    TextView mChooseDir;
    @BindView(R.id.id_total_count)
    TextView mImageCount;
    @BindView(R.id.imageView1)
    ImageView imageView1;
    @BindView(R.id.id_bottom_ly)
    RelativeLayout mBottomLy;


//    private HashMap<String, String> hasSelectedImageMap = new HashMap<String, String>();

//    private ArrayList<String> selectedImages = new ArrayList<String>();

//    private ArrayList<String> hasSelectedImages = new ArrayList<String>();// 已经在发布页面显示的图片，就是已经选中的

    private int imageLimit;

    private ArrayList<ImageBucket> list;

    private AlbumPhotoListAdpater albumPhotoListAdpater;

    private ListImageDirPopupWindow mListImageDirPopupWindow;


    public static void startActivityForResult(Activity activity,int requestCode,int limit){
        Intent intent = new Intent(activity, PhotoListActivity.class);
        intent.putExtra("limit", limit);
        activity.startActivityForResult(intent,requestCode);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_album_list_layout);
        ButterKnife.bind(this);
        initToolbarHelper();
        initViews();
        parseIntent();
        getImages();

    }

    private void initViews() {
        showLoadDialog();
        photoGv.setScrollingCacheEnabled(false);
        /**
         * 为底部的布局设置点击事件，弹出popupWindow
         */
        mBottomLy.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mListImageDirPopupWindow.setAnimationStyle(R.style.photo_dir_anim_popup_dir);
                mListImageDirPopupWindow.showAsDropDown(mBottomLy, 0, 0);
            }
        });
    }


    /**
     * 初始化展示文件夹的popupWindw
     */
    private void initListDirPopupWindw() {
        mListImageDirPopupWindow = new ListImageDirPopupWindow(LayoutParams.MATCH_PARENT, (int) (MyApplication.screenHegiht * 0.7), list,
                LayoutInflater.from(getApplicationContext()).inflate(R.layout.photo_ablun_list_dir, null));
        // 设置选择文件夹的回调
        mListImageDirPopupWindow.setOnImageDirSelected(new ListImageDirPopupWindow.OnImageDirSelected() {

            @Override
            public void selected(ImageBucket floder) {
                ArrayList<ImageItem> images = floder.getFileImageList();
                mImageCount.setText(floder.getPicCount() + "张");
                mChooseDir.setText(floder.getAlbumName());
                albumPhotoListAdpater.updataList(images);
                mListImageDirPopupWindow.dismiss();
            }
        });
    }

    /**
     * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中 完成图片的扫描.
     */
    private void getImages() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }
        showLoadDialog();
        final AlbumHelper albumHelper = AlbumHelper.getHelper();
        albumHelper.init(getApplicationContext());

        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                list = (ArrayList<ImageBucket>) albumHelper.getAlbumBucket(PhotoListActivity.this);
                ArrayList<ImageItem> allImagelist = new ArrayList<ImageItem>();
                allImagelist = albumHelper.getNewPicLists(100);
                String allImageOnePicPath = allImagelist.get(0).getImagePath();
                ImageBucket bucket = new ImageBucket();
                bucket.setAlbumID("-1");
                bucket.setAlbumName("最新图片");
                bucket.setFirstPicPath(allImageOnePicPath);
                bucket.setPicCount(allImagelist.size());
                bucket.setFileImageList(allImagelist);
                list.add(0, bucket);
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        dismissLoadDialog();
                        showGridViewData();
                        initListDirPopupWindw();
                    }
                });
            }

        };
        new Thread(runnable).start();
    }

    Handler handler = new Handler() {
    };

    /**
     * 为View绑定数据
     */
    private void showGridViewData() {
        if (!list.isEmpty()) {
            ArrayList<ImageItem> images = list.get(0).getFileImageList();
            mImageCount.setText(list.get(0).getPicCount() + "张");
            mChooseDir.setText(list.get(0).getAlbumName());
            albumPhotoListAdpater.updataList(images);
        } else {
            mBottomLy.setVisibility(View.GONE);
        }
    }

    ;

    private void parseIntent() {
        Intent intent = getIntent();
        imageLimit = intent.getIntExtra("limit", 0);
        albumPhotoListAdpater = new AlbumPhotoListAdpater(this);
        albumPhotoListAdpater.setImageLimit(imageLimit);
        photoGv.setAdapter(albumPhotoListAdpater);
    }

    /**
     * init the toolbar
     */
    protected void initToolbarHelper() {
        this.setSupportActionBar(this.toolbar);
        getSupportActionBar().setTitle("选择照片");
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.menu_image_confim, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_confim:
                HashMap<String, String> hasSelectedImageMap = albumPhotoListAdpater.getSelectImageMap();
                ArrayList<String> selectedImages = new ArrayList<String>();
                if (hasSelectedImageMap.size() == 0) {
                    ToastUtil.showToast(this, "你还没有选择图片");
                } else {
                    showLoadDialog();
                    ArrayList<String> pathList = new ArrayList<String>();
                    Collection<String> c = hasSelectedImageMap.values();
                    Iterator<String> it = c.iterator();
                    for (; it.hasNext(); ) {
                        pathList.add(it.next());
                    }

                    for (int i = 0; i < pathList.size(); i++) {
                        selectedImages.add(pathList.get(i));
                    }
                    dismissLoadDialog();
                    if (selectedImages.size() == 0) {
                        ToastUtil.showToast(this, "你还没有选择图片");
                    } else {
                        Intent data = new Intent();
                        data.putExtra("list", selectedImages);
                        setResult(RESULT_OK, data);
                        finish();
                    }

                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}
